<template>
  <div v-loading="loading" class="clearfix">
    <el-form ref="item" :model="item" label-width="100px" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="WEB封面：">
            <uploadImg
              remark="直播封面"
              :list="webPhotoList"
              type-code="IMAGE_WEB_LIVE_COVER"
              :data-id="this.$props.id"
              @changeadvert="changeadvertWeb"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="APP封面：">
            <uploadImg
              remark="直播封面"
              :list="appPhotoList"
              type-code="IMAGE_APP_LIVE_COVER"
              :data-id="this.$props.id"
              @changeadvert="changeadvertApp"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="直播标题：" prop="tittle">
            <el-input v-model="item.tittle" style="width:180px;" placeholder="直播标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="直播时长：">
            <el-input v-model="item.duration" style="width:180px;" placeholder="直播时长" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="直播类型：">
            <el-select v-model="item.liveType" style="width:180px;" clearable placeholder="直播类型">
              <el-option
                v-for="item in liveType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="showProjectId" :span="12">
          <el-form-item label="商机：">
            <el-select v-model="item.projectId" style="width:180px;" clearable placeholder="请选择">
              <el-option
                v-for="item in projectIdArr"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="!isCreate" label="直播标识：">
            <el-select
              v-model="item.identification"
              style="width:180px;"
              clearable
              placeholder="直播标识"
            >
              <el-option
                v-for="item in identification"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="直播顾问：">
            <el-tag
              v-for="(tag,index) in dynamicTags"
              :key="index"
              type="info"
              size="medium"
              style="background:#fff;"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >{{ tag }}</el-tag>
            <el-autocomplete
              v-if="inputVisible"
              ref="saveTagInput"
              v-model="inputValue"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入内容"
              @select="handleSelect"
            />
            <el-button v-else class="button-new-tag" @click="showInput">+ 添加顾问</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="tagsArr.length">
        <el-col :span="24">
          <el-form-item label="直播标签：">
            <NewTags :data="tagsArr" :init-data="initDataArr" @changeTag="changeLabel" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否上架：">
            <el-checkbox v-model="item.status" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="直播排序：">
            <el-input v-model="item.sort" style="width:180px;" placeholder="直播排序" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="display:flex;justify-content:center;">
      <el-button style="margin:25px 0;" type="primary" @click="submit">保 存</el-button>
    </div>
  </div>
</template>

<script>
const item = {
  duration: null, // 直播时长
  historicalNumber: null, // 历史观看人数
  id: "", //
  identification: 0, // 直播标识
  label: "", // 直播标签
  liveCover: "", // 直播封面
  liveType: null, // 直播的类型
  liveUrl: "", // 直播的地址
  projectId: "", // 商机的ID
  startTime: "", // 直播开始时间
  status: false, // 是否上架
  tittle: "", // 直播标题
  memberId: "",
  sort: null
};
import { createDics } from "~/utils/util";
import uploadImg from "~/components/commom/uploadImg";
import mmUrl from "~/utils/utilUrl";
import NewTags from "~/components/commom/newTags";

export default {
  components: {
    uploadImg,
    NewTags
  },
  props: ["id"],
  data() {
    return {
      memberIdArr: [],
      dynamicTags: [],
      inputValue: "",
      inputVisible: false,
      questionCreate: true,
      dics: {},
      members: [],
      isCreateText: true,
      initDataArr: [],
      showProjectId: false, // 是否显示商机
      dataId: this.$props.id,
      isCreate: this.$props.id === "create",
      loading: false,
      webPhotoList: [],
      appPhotoList: [],
      description: "",
      contentId: "",
      projectIdArr: [],
      tagsArr: [], // label数组
      identification: [
        {
          label: "暂未开播",
          value: 0
        },
        {
          label: "正在直播",
          value: 1
        }
      ],
      liveType: [
        {
          label: "公开课",
          value: 0
        },
        {
          label: "非公开课",
          value: 1
        }
      ],
      item,
      webPhoto: "",
      appPhoto: "",
      appPhotoObj: "",
      webPhotoObj: "",
      webSuccess: null,
      appSuccess: null,
      rules: {
        tittle: [
          { required: true, message: "直播标题必须填写", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    "item.liveType"(newName) {
      if (newName === 0) {
        this.showProjectId = false;
        this.projectId = "";
      } else if (newName === 1) {
        this.showProjectId = true;
      }
    }
  },
  mounted() {
    this.getInit();
    this.getLabel();
  },
  methods: {
    createStateFilter(queryString) {
      return state => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.members.slice();
      restaurants = restaurants.map(v => {
        return {
          value: v.nickName,
          id: v.id
        };
      });
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 30 * Math.random());
    },
    handleSelect(items) {
      this.item.memberId
        ? (this.item.memberId += `,${items.id}`)
        : (this.item.memberId += items.id);
      this.memberIdArr.push(items);
      const inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    handleClose(tag) {
      const { id } = this.memberIdArr.filter(v => v.value === tag)[0];
      const result = this.item.memberId.replace(id, "");
      this.item.memberId = result
        ? result
            .split(",")
            .filter(v => v !== "")
            .join(",")
        : "";
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    changeLabel(res) {
      this.item.label = JSON.stringify(res);
    },
    getInit() {
      this.$post({
        url: this.isCreate ? mmUrl.live.load : mmUrl.live.loadEdit,
        data: {
          id: this.isCreate ? "" : this.dataId
        }
      }).then(res => {
        this.loading = false;
        this.projectIdArr = res.projects;
        this.members = res.members;
        this.dics = createDics(res.dics, "dicCode");
        if (!this.isCreate) {
          this.item = res.item;
          const resultArr = [];
          const memberIdArr = [];
          res.item.memberId
            ? res.item.memberId.split(",").forEach(v => {
                res.members.forEach(z => {
                  if (z.id === v) {
                    resultArr.push(z.nickName);
                    memberIdArr.push({
                      value: z.nickName,
                      id: z.id
                    });
                  }
                });
              })
            : "";
          this.memberIdArr = memberIdArr;
          this.dynamicTags = resultArr;
          res.questions.map(v => {
            v.status = true;
          });
          this.questionArr = res.questions;
          this.questionCreate = !res.questions.length;
          this.initDataArr = res.item.label ? JSON.parse(res.item.label) : [];
          this.getPhoto("IMAGE_WEB_LIVE_COVER").then(
            res => (this.webPhotoList = res)
          );
          this.getPhoto("IMAGE_APP_LIVE_COVER").then(
            res => (this.appPhotoList = res)
          );
        }
      });
    },
    changeadvertWeb(res) {
      this.webPhoto = res.fileUrl;
      this.webPhotoObj = res;
    },
    changeadvertApp(res) {
      this.appPhoto = res.fileUrl;
      this.appPhotoObj = res;
    },
    getPhoto(res) {
      return new Promise((resolve, reject) => {
        this.$post({
          url: mmUrl.file.getfiles,
          data: {
            dataId: this.$props.id,
            typeCode: res
          }
        })
          .then(res => {
            resolve(res.length ? res : "");
          })
          .catch(() => reject());
      });
    },
    getLabel() {
      this.$post({
        url: mmUrl.label.pageLoad,
        data: {
          keyword: "",
          page: {
            maxResultCount: 0,
            pageNo: 0,
            pageSize: 10,
            skipCount: 0
          },
          type: 0
        }
      }).then(res => {
        this.tagsArr = res.items.items;
      });
    },
    submitPhoto(res) {
      return new Promise((resolve, reject) => {
        this.$post({
          url: mmUrl.file.uploadFile,
          data: {
            items: [res]
          }
        })
          .then(() => {
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    },
    submit() {
      this.$refs["item"].validate(valid => {
        if (valid) {
          if (this.item.memberId) {
            if (this.item.memberId.includes("null,")) {
              this.item.memberId = this.item.memberId.replace(
                new RegExp(/null,/g),
                ""
              );
            } else if (this.item.memberId.includes("null")) {
              this.item.memberId = this.item.memberId.replace(
                new RegExp(/null/g),
                ""
              );
            }
          }
          const result = {};
          result.item = JSON.parse(JSON.stringify(this.item));
          result.questionList = [];
          this.$post({
            url: this.isCreate ? mmUrl.live.create : mmUrl.live.editor,
            data: result
          }).then(res => {
            this.webPhotoObj ? this.submitPhoto(this.webPhotoObj) : "";
            this.appPhotoObj ? this.submitPhoto(this.appPhotoObj) : "";
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.getInit();
            this.$emit("closeDialog");
          });
        }
      });
    }
  }
};
</script>

<style lang='scss'>
.hoverDeleteIcon {
  :hover {
    color: red;
  }
}
</style>
